<template>
    <section class="form-warpper">
        <el-table :data="state.ruleForm" style="width: 100%" border>
            <el-table-column label="子女姓名">
                <template #default="scope">
                    <el-input placeholder="请输入子女姓名" size="mini" v-model="scope.row.childrenName"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="子女类型">
                <template #default="scope">
                    <el-radio-group v-model="scope.row.childrenType">
                        <el-radio :value="1">子</el-radio>
                        <el-radio :value="2">女</el-radio>
                    </el-radio-group>
                </template>
            </el-table-column>
            <el-table-column label="子女出生日期">
                <template #default="scope">
                    <el-date-picker value-format="YYYY-MM-DD" 
                        v-model="scope.row.childrenBirthday" type="date" 
                        placeholder="请选择出生日期" size="mini" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="scope">
                    <el-button plan type="danger" size="mini" @click="removeHanlde(scope.row.id)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-button plan type="primary" style="margin-top: 15px;" size="middle" @click="addReport">+ 新增</el-button>
    </section>
</template>

<script setup lang="ts">
import { reactive, defineExpose } from 'vue'
import { formatDate } from '/@/utils/formatTime'

interface IFormData {
    id: string | number, 
    childrenName: string, 
    childrenType: string, 
    childrenBirthday: string, 
}

const initData = () => ({
    childrenName: '', 
    childrenBirthday: '', 
    childrenType: '', 
    id: `${Date.now()}`
});

// 定义table数据
const state = reactive({
    ruleForm: [
        { id: '', childrenName: '', childrenType: '', childrenBirthday: ''}
    ] as Array<IFormData>
})

// 添加行
const addReport = () => {
    state.ruleForm.push(initData())
}

// 删除行
const removeHanlde = (id: string) => {
    state.ruleForm = state.ruleForm.filter(item => item.id !== id)
}

// 获取数据
const getData = () => {
    if(!state.ruleForm.length) {
        return [initData()]
    }
    return state.ruleForm 
}

const setData = (list: Array<IFormData > | Array<any>) => { 
    if(list.length) {
        state.ruleForm = [];
        (list || []).forEach((item, index) => {
            state.ruleForm.push({
                id: item.id, 
                childrenName: item.childrenName, 
                childrenType: item.childrenType, 
                childrenBirthday: formatDate(new Date(item.childrenBirthday), 'YYYY-mm-dd HH:MM:SS'),
            })
        }) 
    } 
}

// 暴露获取表单数据方法
defineExpose({ getData,setData })
</script>